#!/usr/bin/env python

import re
from BeautifulSoup import BeautifulSoup
from distutils import version
import sys
import urllib2

def findLatest(url):  
	"""Find the latest vercion of a source tarball in a FTP folder. Part \
			vlmigratepackages."""

	# Find what we need from url
	sp = url.rsplit('/', 1)

	folder = sp[0]
	print 'Http folder:', folder

	filename = sp[-1]
	print 'Filename: ', filename

	name = filename.split('-', 1)[0]
	print 'Name: ', name

	ver = re.match('.*-(.*)\.tar\.[bg]z\d*', filename).group(1)
	print 'Version: %s' % (ver)
	
	# get html
	doc = urllib2.urlopen(folder)
	html = doc.read()
	soup = BeautifulSoup(html)
	
	# get a remote list of files
	# we need to control in some way that we are comparing versions of the same file
	list = soup.findAll('a', text = re.compile(name + '.*\.tar\.[bg]z\d*$'))

	# find the latest
	latest = ver
	for i in list:
		rname = i.rsplit('-', 1)[0]
		if rname == name and re.match('.*.tar.[bg]z\d*$', i):
			rver = re.match('.*-(.*)\.tar\.[bg]z\d*', i).group(1)
			if version.LooseVersion(rver) > version.LooseVersion(latest):
				latest = rver
				slatest = i

	return '%s/%s' % (sp[0], slatest)


if len(sys.argv) != 2:
	sys.stderr.write('USAGE: findLatest.py <URL>\n')
else:
	print 'Latest: %s' % (findLatest(sys.argv[1]))

# Example: ./findLatestHtml.py http://ftp.gnu.org/pub/gnu/cpio/cpio-2.4.tar.bz2
# vim: set tabstop=4 shiftwidth=4 foldmethod=marker : ##
